package com.csdj.server.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csdj.server.mapper.MenuMapper;
import com.csdj.server.pojo.Admin;
import com.csdj.server.pojo.Menu;
import com.csdj.server.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ZouLi
 * @since 2022-12-12
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    // 注入mapper
    @Autowired(required = false)
    private MenuMapper menuMapper;
    // 注入redis
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<Menu> getMenusByUserId() {
        Admin admin = (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        ValueOperations<String, Object> redis = redisTemplate.opsForValue();
        List<Menu> menus = (List<Menu>) redis.get("menu_" + admin.getId());
        if (CollectionUtils.isEmpty(menus)) {
            menus = menuMapper.getMenusByUserId(admin.getId());
            redis.set("menu_" + admin.getId(), menus);
        }
        return menus;
    }

    @Override
    public List<Menu> getMenusWithRole() {
        return menuMapper.getMenusWithRole();
    }

    @Override
    public List<Menu> getAllMenus() {
        return menuMapper.getAllMenus();
    }
}
